package com.UBC417.termproject.Data;

import java.util.*;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.SortDirection;
import com.google.appengine.api.datastore.Transaction;
import com.google.appengine.api.datastore.TransactionOptions;

@SuppressWarnings("deprecation")
public class Seller extends User {
	
	public static String CreateAuction(String itemName, String description, String basePrice, 
			String userId, Date startDate, Date endDate, String status){
		DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
		
		// add new auction
		Entity e = new Entity("Auction");
		Date d = new Date();
		e.setProperty("name", itemName);
		e.setProperty("dateCreated", d);
		e.setProperty("userId",userId);
		e.setProperty("startDate", startDate);
		e.setProperty("endDate", endDate);
		e.setProperty("status", status);
		
		ds.put(e);
		String appId = KeyFactory.keyToString(e.getKey());
		
		// add new item associated with the auction
		e = new Entity("Item");
		e.setProperty("name", itemName);
		e.setProperty("description",description);
		e.setProperty("basePrice", Double.parseDouble(basePrice));
		e.setProperty("auctionId", appId);
		e.setProperty("dateCreated", d);
		e.setProperty("status", status);
		
		ds.put(e);
		return KeyFactory.keyToString(e.getKey());
	}
	
	public static List<Auction> ViewActiveAuction(String userId){
		DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
		
		Query query = new Query("Auction").addFilter("status", Query.FilterOperator.EQUAL, "Open").addSort("endDate", SortDirection.ASCENDING);
		Iterable<Entity> entries = ds.prepare(query).asIterable();
		List<Auction> items = new ArrayList<Auction>();
		for(Entity e : entries){
			if (e.getProperty("userId").equals(userId)){
				Auction a = new Auction();
				a.setName((String)e.getProperty("name"));
				a.setUserId((String)e.getProperty("userId"));
				a.setStartTime((Date)e.getProperty("startDate"));
				a.setEndTime((Date)e.getProperty("endDate"));
				a.setStatus((String)e.getProperty("status"));
				a.setId(KeyFactory.keyToString(e.getKey()));
				items.add(a);
			}			
		}
		return items;
		
	}
	
	public static List<Auction> ViewAllAuction(String userId){
		DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
		
		Query query = new Query("Auction").addFilter("status", Query.FilterOperator.NOT_EQUAL, "Open").addSort("status").addSort("endDate", SortDirection.ASCENDING);
		Iterable<Entity> entries = ds.prepare(query).asIterable();
		List<Auction> items = new ArrayList<Auction>();
		for(Entity e : entries){
			if (e.getProperty("userId").equals(userId)){
				Auction a = new Auction();
				a.setName((String)e.getProperty("name"));
				a.setUserId((String)e.getProperty("userId"));
				a.setStartTime((Date)e.getProperty("startDate"));
				a.setEndTime((Date)e.getProperty("endDate"));
				a.setStatus((String)e.getProperty("status"));
				a.setId(KeyFactory.keyToString(e.getKey()));
				items.add(a);
			}			
		}
		return items;
		
	}
	
	public static void CancelAuction(String auctionId){
		DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
		
		int retries = 3;
		while (true) {
			TransactionOptions options = TransactionOptions.Builder.withXG(true);
			Transaction txn = ds.beginTransaction(options);
			
			try {
				Entity item = ds.get(KeyFactory.stringToKey(auctionId));
				item.setProperty("status", "Cancelled");
				ds.put(item);
				Query query = new Query("Item").addFilter("auctionId", Query.FilterOperator.EQUAL, auctionId);
				Iterable<Entity> entries = ds.prepare(query).asIterable();
				for(Entity e : entries){
					e.setProperty("status", "Cancelled");
					ds.put(e);
				}
				txn.commit();
		        break;
			} catch (EntityNotFoundException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			catch (ConcurrentModificationException e) {
		        if (retries == 0) {
		            throw e;
		        }
		        // Allow retry to occur
		        --retries;
		    } finally {
		        if (txn.isActive()) {
		            txn.rollback();
		        }
		    }
		}
	}
	
	public static void CloseInactiveUserAuction(String userId){
		DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
		String status = "User Unsubscribed";
		
		Query query = new Query("Auction").addFilter("userId",Query.FilterOperator.EQUAL,userId);
		Iterable<Entity> entries = ds.prepare(query).asIterable();
		for (Entity e : entries){
			e.setProperty("status", status);
			ds.put(e);
			query = new Query("Item").addFilter("auctionId", Query.FilterOperator.EQUAL, KeyFactory.keyToString(e.getKey()));
			Iterable<Entity> entries2 = ds.prepare(query).asIterable();
			for(Entity e2 : entries2){
				e2.setProperty("status", status);
				ds.put(e2);
			}
		}	
	}

}
